<template>
  <div id="app">
    <el-container>
      <!-- 顶部导航栏 -->
      <div class="top_bar">
        <div class="nav">
          <a href="javascript:" style="fontSize:14px">
            <router-link to="/"> 欢迎来到书店 </router-link>
          </a>
          <ul>
            <li v-if="!user">
              <span @click="setShowLoginDialog">
                <a href="javascript:">登录</a>
              </span>
              <span>|</span>
              <span @click="registerDialogVisible = true">
                <a href="javascript:">注册</a>
              </span>
            </li>
            <li v-else>欢迎!{{ user }}</li>
            <li>
              <a href="#"> <router-link to="/user"> 个人中心</router-link></a>
            </li>

            <li>
              <a href="#">
                <router-link to="/shop">购物车</router-link>
              </a>
            </li>

            <li>
              <a href="#">
                <router-link to="/myorderlist"> 我的订单</router-link></a
              >
            </li>

            <li>
              <router-link to="/sell">
                <a href="#">出售图书</a>
              </router-link>
            </li>

            <li v-if="user">
              <span @click="loginout"><a href="#">退出</a></span>
            </li>
          </ul>
        </div>
      </div>
      <!-- 头部 -->
      <div class="head">
        <div class="head_box">
          <div class="logo">
            <router-link to="/main">
              <img src="./assets/images/logo3.jpg" alt="" />
            </router-link>
          </div>
          <div>
            <ul>
              <router-link to="/main">
                <li>首页</li>
              </router-link>
              <router-link to="/sell">
                <li>出售</li>
              </router-link>
            </ul>
          </div>
        </div>
      </div>
      <!-- end -->
      <!-- 主体部分 -->
      <el-main>
        <!-- 路由占位符 -->
        <router-view></router-view>
      </el-main>

      <!-- 底部部分 -->
      <el-footer>
        <div class="footer">
          <ul>
            <li>关于我们</li>
            <li>申请合作</li>
            <li>隐私政策</li>
            <li>服务条款</li>
            <li>帮助</li>
            <li>友情链接</li>
          </ul>
          <div class="banquan">© 2021 by 校园二手书交易 deng</div>
        </div>
      </el-footer>
    </el-container>

    <!-- 登陆弹窗 -->
    <el-dialog
      title="登陆"
      :visible.sync="showLogin"
      width="25%"
      @close="loginHandleClose"
      class="login"
      :close-on-click-modal="false"
    >
      <!-- 登录表单 -->
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginFormRules"
        label-width="0px"
        class="login_form"
      >
        <!-- 手机号 -->
        <el-form-item prop="phone">
          <el-input v-model="loginForm.phone" placeholder="手机号"></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item prop="password">
          <el-input
            type="password"
            v-model="loginForm.password"
            placeholder="密码"
          ></el-input>
        </el-form-item>
        <!-- 按钮 -->
        <el-form-item class="btns">
          <div style="margin-right:20px">
            <el-button type="primary" @click="login">登录</el-button>
          </div>
          <div class="forget" @click="forgetPass">忘记密码？</div>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 注册弹窗 -->
    <el-dialog
      title="注册"
      :visible.sync="registerDialogVisible"
      width="30%"
      @close="registerHandleClose"
      :close-on-click-modal="false"
    >
      <!-- 注册表单 -->
      <el-form
        ref="registerFormRef"
        :model="registerForm"
        :rules="registerFormRules"
        label-width="0px"
      >
        <!-- 手机号 -->
        <el-form-item prop="phone">
          <el-input
            v-model="registerForm.phone"
            placeholder="手机号"
          ></el-input>
        </el-form-item>
        <!-- 邮箱 -->
        <el-form-item prop="email">
          <el-input v-model="registerForm.email" placeholder="邮箱"></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item prop="password">
          <el-input
            type="password"
            v-model="registerForm.password"
            placeholder="密码"
          ></el-input>
        </el-form-item>
        <!-- 昵称 -->
        <el-form-item prop="username">
          <el-input
            v-model="registerForm.username"
            placeholder="昵称"
          ></el-input>
        </el-form-item>
        <!-- 所在学校 -->
        <el-form-item prop="school">
          <el-input
            v-model="registerForm.school"
            placeholder="所在学校"
          ></el-input>
        </el-form-item>
        <!-- 按钮 -->
        <el-form-item class="btns">
          <el-button type="primary" @click="register">注册</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 重置密码弹窗 -->
    <el-dialog
      title="重置密码"
      :visible.sync="resetPassDialogVisible"
      width="350px"
      @close="resetPassHandleClose"
      :close-on-click-modal="false"
    >
      <!-- 重置密码表单 -->
      <el-form
        ref="resetPassFormRef"
        :model="resetPassForm"
        :rules="resetPassFormRules"
        label-width="0px"
      >
        <!-- 注册邮箱 -->
        <el-form-item prop="email">
          <el-input
            v-model="resetPassForm.email"
            placeholder="注册邮箱"
          ></el-input>
        </el-form-item>
        <!-- 新密码 -->
        <el-form-item prop="newPassWord">
          <el-input
            type="password"
            v-model="resetPassForm.newPassWord"
            placeholder="新密码"
          ></el-input>
        </el-form-item>
        <!-- 重复密码 -->
        <el-form-item prop="repeatPassWord">
          <el-input
            type="password"
            v-model="resetPassForm.repeatPassWord"
            placeholder="重复密码"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-col :span="11" style="margin-right:10px">
            <!-- 验证码 -->
            <el-form-item prop="yanzhengma">
              <el-input
                v-model="resetPassForm.yanzhengma"
                placeholder="验证码"
              ></el-input> </el-form-item
          ></el-col>
          <el-col :span="11">
            <!-- 发送按钮 -->
            <el-form-item class="btns">
              <el-button v-show="show" type="warning" @click="sendEmail"
                >发送验证码</el-button
              >
              <el-button v-show="!show" type="warning" disabled
                >{{ count }}秒后重新发送</el-button
              >
            </el-form-item></el-col
          >
        </el-form-item>
        <!-- 按钮 -->
        <el-form-item class="btns">
          <el-button type="primary" @click="resetPassWord">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { mapActions, mapState, mapGetters } from 'vuex'
export default {
  name: 'app',
  data() {
    // 验证手机号码的规则
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^1[34578]\d{9}$/
      if (regMobile.test(value)) {
        return cb()
      }
      // 返回一个错误提示
      cb(new Error('请输入合法的手机号码'))
    }
    // 验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      if (regEmail.test(value)) {
        return cb()
      }
      // 返回一个错误提示
      cb(new Error('请输入合法的邮箱'))
    }
    // 验证重复密码
    var checkRepeatPassword = (rule, value, cb) => {
      if (value !== this.resetPassForm.newPassWord) {
        // 返回一个错误提示
        cb(new Error('重复密码与新密码不符'))
      }
      cb()
    }
    return {
      // 登陆弹窗显示判断
      loginDialogVisible: false,
      // 登陆表单
      loginForm: {
        phone: '',
        password: ''
      },
      loginFormRules: {
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          {
            validator: checkMobile,
            message: '请输入正确的手机号',
            trigger: 'blur'
          }
        ],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      },
      // 注册弹窗显示判断
      registerDialogVisible: false,
      // 注册表单
      registerForm: {
        phone: '',
        email: '',
        password: '',
        username: '',
        school: ''
      },
      registerFormRules: {
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          {
            validator: checkMobile,
            message: '请输入合法的手机号',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            validator: checkEmail,
            message: '请输入合法的邮箱',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '密码在6~15个字符之间',
            trigger: 'blur'
          }
        ],
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          {
            min: 2,
            max: 10,
            message: '用户名在2~10个字符之间',
            trigger: 'blur'
          }
        ],
        school: [
          { required: true, message: '请输入所在学校', trigger: 'blur' },
          {
            min: 4,
            max: 20,
            message: '用户名在4~20个字符之间',
            trigger: 'blur'
          }
        ]
      },
      // 重置密码弹窗显示判断
      resetPassDialogVisible: false,
      // 重置密码表单
      resetPassForm: {
        email: '',
        newPassWord: '',
        repeatPassWord: '',
        yanzhengma: ''
      },
      resetPassFormRules: {
        email: [
          { required: true, message: '请输入注册邮箱', trigger: 'blur' },
          {
            validator: checkEmail,
            message: '请输入合法的邮箱',
            trigger: 'blur'
          }
        ],
        newPassWord: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '密码在6~15个字符之间',
            trigger: 'blur'
          }
        ],
        repeatPassWord: [
          { required: true, message: '重复密码不能为空', trigger: 'blur' },
          {
            validator: checkRepeatPassword,
            message: '重复密码与新密码不符',
            trigger: 'blur'
          }
        ],
        yanzhengma: [
          { required: true, message: '验证码不能为空', trigger: 'blur' }
        ]
      },
      // 随机数
      randomNum: '',
      // 按钮显示
      show: true,
      // 倒计时
      count: '',
      // 定时器
      timer: null
    }
  },
  created() {
    if (sessionStorage.getItem('user')) {
      // 如果已经登录，设置vuex登录状态
      this.setUser(sessionStorage.getItem('user'))
    }
  },
  watch: {
    // 获取vuex的登录状态
    getUser: async function(val) {
      if (val === '') {
        // 用户没有登录
        this.setShoppingCart([])
      } else {
        // 用户已经登录,获取该用户的购物车信息
        const { data: res } = await this.$http.get(
          'shopcart/getShopCart/' + val
        )
        if (res.code !== 200) return this.$message.error('获取购物车信息失败')
        res.data.forEach(item => {
          item.ischeck = item.ischeck >= 1
        })
        this.setShoppingCart(res.data)
      }
    }
  },
  methods: {
    ...mapActions('user', ['setShowLogin', 'setUser']),
    ...mapActions('shopcart', ['setShoppingCart']),
    // 打开登陆弹窗
    setShowLoginDialog() {
      this.setShowLogin(true)
    },
    // 登陆弹窗关闭
    loginHandleClose() {
      this.$refs.loginFormRef.resetFields()
    },
    // 登陆
    login() {
      this.$refs.loginFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(
          'user/userlogin',
          this.loginForm
        )
        if (res.status !== 200) return this.$message.error('手机号与密码不匹配')
        else {
          this.$message.success('登陆成功')
          // 1.将登陆成功之后的token,保存到客户端的sessionStorage中
          // 1.1 项目中除了登录之外的其它API接口，必须在登陆之后才能访问
          // 1.2 token 只应在当前网站打开期间生效，所以将token保存在sessionStorage中
          // console.log(res.data.username)
          window.sessionStorage.setItem('token', res.token)
          window.sessionStorage.setItem('user', res.data.username.toString())
          // 2.关闭弹窗
          this.setShowLogin(false)
          // 存储用户信息
          this.setUser(sessionStorage.getItem('user'))
          this.$router.go(0)
        }
      })
    },
    // 注册弹窗关闭
    registerHandleClose() {
      this.$refs.registerFormRef.resetFields()
    },
    // 注册
    register() {
      this.$refs.registerFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(
          'user/addUser',
          this.registerForm
        )
        if (res.status !== 200) return this.$message.error('注册失败')
        else {
          this.$message.success('注册成功')
          this.registerDialogVisible = false
        }
      })
    },
    // 忘记密码
    forgetPass() {
      this.showLogin = false
      this.resetPassDialogVisible = true
    },
    // 重置密码框关闭
    resetPassHandleClose() {
      this.$refs.resetPassFormRef.resetFields()
    },
    // 发送验证码
    sendEmail() {
      this.$refs.resetPassFormRef.validateField('email', async valid => {
        if (valid) return this.$message.warning('请输入合法邮箱')
        this.randomNum = this.createSixNum()
        console.log(this.resetPassForm.email, this.randomNum)
        const { data: res } = await this.$http.get('user/email', {
          params: { email: this.resetPassForm.email, randomNum: this.randomNum }
        })
        if (res.code == 400) return this.$message.error('发送出错')
        if (res.code == 404) return this.$message.warning('该注册邮箱不存在')
        // 倒计时
        const TIME_COUNT = 60
        if (!this.timer) {
          this.count = TIME_COUNT
          this.show = false
          this.timer = setInterval(() => {
            if (this.count > 0 && this.count <= TIME_COUNT) {
              this.count--
            } else {
              this.show = true
              // 清除定时器
              clearInterval(this.timer)
              this.timer = null
            }
          }, 1000)
        }
        console.log(res, 111)
      })
    },
    // 重置密码
    resetPassWord() {
      this.$refs.resetPassFormRef.validate(async valid => {
        if (!valid) return
        if (this.resetPassForm.yanzhengma !== this.randomNum) {
          return this.$message.warning('验证码错误')
        }
        const { data: res } = await this.$http.post(
          'user/changePwdByEmail',
          this.resetPassForm
        )
        if (res.code !== 200) return this.$message.error('重置密码失败')
        this.$message.success('重置密码成功')
        this.resetPassDialogVisible = false
      })
    },
    // 退出登陆
    loginout() {
      window.sessionStorage.clear()
      this.setUser('')
      this.$router.go(0)
    },
    // 生成随机数
    createSixNum() {
      var Num = ''
      for (var i = 0; i < 6; i++) {
        Num += Math.floor(Math.random() * 10)
      }
      return Num
    }
  },
  computed: {
    ...mapGetters('user', ['getUser', 'getNum']),
    ...mapGetters('shopcart', ['getShoppingCart']),
    ...mapState({
      showLogin: state => state.user.showLogin,
      user: state => state.user.user
    }),
    showLogin: {
      get() {
        return this.$store.state.user.showLogin
      },
      set(val) {
        this.$store.state.user.showLogin = val
      }
    },
    user: {
      get() {
        return this.$store.state.user.user
      },
      set(val) {
        this.$store.state.user.user = val
      }
    }
  }
}
</script>
<style lang="scss" scoped>
/* 顶部导航栏 */
.top_bar {
  width: 100%;
  height: 36px;
  background-color: rgb(51, 51, 51);
  color: rgb(210, 172, 107);
}
.nav {
  width: 1000px;
  height: 36px;
  margin: 0 auto;
  line-height: 36px;
  font-size: 13px;
  a {
    float: left;
    color: rgb(210, 172, 107);
  }
  ul {
    float: right;
    li {
      float: left;
      a {
        margin: 0 5px;
        font-size: 13px;
        color: rgb(210, 172, 107);
      }
      a:hover {
        color: red;
      }
      span {
        float: left;
      }
    }
  }
}
.head {
  height: 66px;
  padding: 6px 0;
  background-color: rgb(255, 255, 255);
  border-bottom: 1px solid rgb(245, 245, 245);

  .head_box {
    width: 1000px;
    margin: 0 auto;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .logo {
      img {
        width: 130px;
        height: 73px;
      }
    }
    ul {
      display: flex;
      align-items: center;
      li {
        width: 100px;
        color: rgb(100, 100, 100);
        font-size: 20px;
        font-weight: bolder;
      }
    }
  }
}
// 主体
.el-main {
  padding: 0;
  width: 1000px;
  margin: 0 auto;
  margin-top: 10px;
}
.el-footer {
  margin-top: 20px;
  background-color: rgb(102, 102, 102);
  height: 50px;
}
.footer {
  width: 1000px;
  margin: 0 auto;
  height: 50px;
  display: flex;
  justify-content: space-between;
  ul {
    display: flex;
    color: #999;
    font-size: 12px;
    li {
      margin: 10px;
      cursor: pointer;
    }
  }
  .banquan {
    display: flex;
    color: #999;
    font-size: 12px;
    margin: 10px;
  }
}
// 忘记
/deep/ .btns .el-form-item__content {
  display: flex;
}
.forget {
  cursor: pointer;
  &:hover {
    color: rgb(210, 172, 107);
  }
}
</style>
